// ==UserScript==
// @grant        GM_getResourceText
// @grant        GM_addStyle
// @grant        GM_xmlhttpRequest
// @name         美团数据导出
// @namespace    https://gitee.com/xvcer/tampermonkey-meituan
// @version      1.0.9
// @author       xpure@foxmail.com
// @updateURL    https://gitee.com/xvcer/tampermonkey-meituan/raw/master/version
// @downloadURL  https://gitee.com/xvcer/tampermonkey-meituan/raw/master/main.js
// @require      http://coffeescript.org/v2/browser-compiler-legacy/coffeescript.js
// @require      https://cdn.jsdelivr.net/combine/npm/jquery@3,npm/papaparse@4,npm/@fancyapps/fancybox@3,npm/lodash@4
// @resource     cssFancybox https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css
// @resource     cssMain https://gitee.com/xvcer/tampermonkey-meituan/raw/master/main.css
// @include      https://*.meituan.com/s/*
// @include      https://www.meituan.com/error/403
// ==/UserScript==

function addCss(name) {
  GM_addStyle(
    GM_getResourceText(name)
  )
}

(function() {
  addCss('cssFancybox')
  addCss('cssMain')
})();
const CITY_EN=["bj","sh","gz","sz","tj","xa","cq","hz","nj","wh","cd","as","anqing","ay","anshun","ankang","aq","anyue","anlushi","aks","anzhouqu","atushishi","aj","als","anping","anxi","anning","anhua","alaer","anfu","aletaishi","achengqu","am","alt","al","ab","bt","bd","bengbu","bozhou","bz","baoji","bc","hbbazhou","byne","bh","baise","bazhong","bijie","bs","benxi","by","baishan","bishan","baiquanxian","baichengxian","baoying","beiliu","boai","bachuxian","baofeng","boxing","biyang","binxian","bayanxian","boshan","binyang","botou","boluoxian","bobaixian","beizhenshi","beianshi","binhai","beipei","betl","baz","cz","cc","chs","cangzhou","changzhi","cixi","chuzhou","changde","chenzhou","chengde","changshu","chifeng","changjiangxian","chaozhou","ch","cg","cangnan","changyi","conghua","chizhou","cy","chx","chenggu","changle","cmx","cx","chongzhou","chongzuo","ca","chengdexian","changlecl","caofeidian","cixian","changyuan","chengan","changli","cenxi","chiping","caoxian","changji","changting","chaoan","changshou","changshan","chishui","cili","changningshi","chalingxian","changfengxian","cangxixian","changqingqu","chongmingqu","chengwuxian","chengjiangxian","cb","changdu","dl","dg","dt","dq","dandong","dy","dz","deyang","dazhou","dengzhou","dali","dsq","djy","dx","danyang","danzhou","dongyang","dengfeng","df","dongtai","dazhu","dangyang","deqing","dongkengzhen","dehuishi","dazuqu","daye","dongxing","dbs","dengta","datongshi","dongfang","dongping","dianbai","donghai","dingzhou","dancheng","dalixian","dalateqi","donggang","dawa","dayi","dangshan","dunhua","dongguang","daoxian","daanshi","dinganxian","dianjiang","dongmingxian","dingtaoqu","dingbianxian","dachangzizhixian","dingyuanxian","dongexian","dxal","dh","diqing","dunhuang","erds","ez","es","enping","ems","eminxian","eegn","fz","fs","fy","fuz","fushun","fx","fl","fuqing","fenghua","fc","fuyangfy","fn","fcg","fuminxian","fengcheng","fenyang","fukang","fch","fanxian","fanchang","feixiang","fengqiu","fufeng","fh","fusong","fushunxian","feixian","fogang","fengning","fugou","fengtai","fengxin","fangcheng","fuyuanxian","fenyi","fusuixian","feixixian","fanzhixian","fengxiangxian","fuan","fudingshi","fuguxian","fengjie","fengdu","feidongxian","fengxian","gy","ganzhou","gg","gl","ga","gaozhou","gongyishi","gm","gbd","guangyuan","gaoyou","gr","guanxian","gp","gzl","guangshanxian","gh","gc","gaoping","guangze","guyuan","gaochunqu","gaizhou","gujiao","geermu","gushixian","guanyun","guannan","ganyu","gaoan","guangde","gongqingcheng","gaoyang","gaoling","gongan","gj","gulangyu","gaoxiong","guoluo","gn","ganzi","hf","hrb","hy","hd","huizhou","hu","haikou","huzhou","ha","hn","heze","hshi","hg","hh","hs","hld","hc","huangshan","hlbe","heihe","hb","heyuan","hezhou","hegang","honghe","hanzhong","haining","huidong","huiyang","haicheng","hm","haiyang","huaibei","haian","huazhou","hechuan","hengdian","haidong","heshan","huadian","huachuanxian","huanglingxian","huayin","huanxian","houma","hejiangxian","hami","huozhou","huanghua","hailunshi","hl","hannanqu","helanxian","haiyan","hengshanqu","huaiyang","hanyin","hanshan","hexian","huxian","huixian","huairen","huaxian","huian","hancheng","huarong","huating","hongtong","hekou","huinan","honghu","haicang","huoqiu","hunchun","huaining","huaiyuanxian","huizexian","hejianshi","hepuxian","hengyangxian","hengshanxian","hengdongxian","huangchuanxian","hj","hualian","ht","hx","hnz","huangnan","haibei","hk","jn","jl","jiangyin","jx","jh","jm","jining","jingzhou","jiaozuo","jinjiang","jy","jingmen","jj","jms","jinzhou","jintan","jiyuan","jdz","jq","jixi","jz","jingjiang","ja","js","jr","jiaozhou","jimo","jincheng","jiangdu","jiangshan","jinchang","jianhu","jinzhoushi","jyg","jd","jianyang","jiexiu","jingdongyizuzizh","jiutai","jingguxian","jingxixian","jiaohe","jianyangjy","jiaxian","jintang","jianli","jiangjin","juye","jiaxiang","jinxiang","jinyun","jingshan","jiangyou","junan","jingyangxian","jinhu","jimei","jinsha","jingxian","jianxian","jishuixian","jiangchuanxian","jianghuayaozuziz","jinningxian","jiangyong","jianshuixian","juanchengxian","jingbian","jiayuxian","jzqixian","jinghexian","jianshi","jiayi","jilong","jgs","jzg","km","kunshan","kaifeng","klmy","kaihua","kp","krl","kaiyang","kaiyuanshi","kangxian","kaizhouqu","kenli","kuancheng","kuche","kt","kl","ks","kz","lyg","linyi","luoyang","liuzhou","lz","lc","lf","liaoyang","lishui","la","ls","lasa","ly","linfen","linzhou","lb","luzhou","liaoyuan","lvliang","lps","lj","lw","luohe","liyang","linhai","lx","lk","leiyang","laizhou","linan","laiyang","lufeng","liuyang","lianjiang","ld","liangshan","luquanxian","lincang","linquanxian","lingbao","lsj","ll","linxia","lh","liling","laixi","lechang","lp","langzhong","luquan","lichuan","lhk","linghai","luannan","lingshan","lianzhou","lingshui","lingwushi","lianjiangxian","linqu","laoting","luanxian","luancheng","lushanls","lingshi","linzhang","lintong","lantian","lq","longchang","luyi","liuhe","linyixian","liangshanxian","lijin","linyily","longquan","lingchuan","longyao","leizhou","luanchuan","longyou","lanling","linshu","lianshui","lixian","liaozhong","luopingxian","lianyuanshi","lujiangxian","linying","lanshan","longhui","luxi","lushixian","longhuaxian","luoningxian","lankaoxian","linli","lixin","lingqiuxian","lufengxian","lishuiqu","luxian","luochuanxian","luodingshi","ledong","liangping","lingaoxian","luoyuanxian","luchuanxian","linjiang","ln","linzhi","my","mdj","mm","mas","mz","ms","mentougouqu","mishan","mzl","mhk","ml","mg","mc","mengzhou","mingshuixian","mengjin","muping","meixian","minquan","mianchi","mianzhu","mengyin","mengzishi","mengcheng","menglaxian","miyixian","minhouxian","miaoli","mh","mingwangxing","nb","nn","nc","nt","ny","nd","nanchong","np","scnj","nh","na","nanchuan","nx","ns","ningyuanxian","nehe","nanxiong","nenjiangxian","nanle","nanling","ningyang","ningguo","ningjin","ningjinnj","neiqiu","nangong","neihuang","nanhe","nanbuxian","nanpixian","ninglingxian","nanzhengxian","nq","nujiang","nantou","pt","pj","pds","puyang","panzhihua","pe","pl","pz","px","pn","pd","pengzhou","penglai","pingyang","peixian","ph","pujiang","panshi","pingyuan","pulandian","poyang","pucheng","panxian","pingjiang","puyangxian","pingshan","pingquan","pingyi","pingyu","pingyao","pingguo","pingluoxian","pingyinxian","pingluxian","pingchangxian","pingnanxian","pingtan","penghu","qd","qhd","qz","qj","quzhou","qingyuan","qqhr","qinzhou","qth","qingyang","qa","qingzhou","qidong","qianjiang","qdn","qxn","qianjiangqu","qingtongxiashi","qh","qy","ql","qihe","qn","qixian","quanjiao","qixia","qingtian","qinghe","qingyun","qianshan","qingxian","qidongxian","qinganxian","qixiankaifeng","qinggangxian","qishanxian","qiongzhong","qingyangxian","qingzhen","qijiang","qingxu","qianxixian","qishizhen","qingfeng","qf","rizhao","ruian","rc","rs","rg","rz","rudong","rh","rj","rongchangqu","renshou","renqiu","ruyang","ruili","renxian","ruchengxian","rongxian","ruichang","rkz","sjz","su","sy","sanya","st","sx","songyuan","sg","shaoyang","suqian","shiyan","suzhousz","sd","sr","sq","shz","smx","suizhou","suihua","sys","sw","suining","sl","szs","sp","sm","ss","shangyu","shouguang","shengzhou","shuyang","sheyang","sanhe","shuozhou","shucheng","shilinxian","songmingxian","shaya","shaoshan","shahe","sihui","songzi","shulan","shaodong","suixian","siyang","shawan","shexian","sanyuanxian","suizhong","shanggao","shiquan","sihong","shanxian","shenqiu","sanmen","suiningxian","shangcai","suichang","shidao","shifang","shanghang","songxian","shenxian","shehong","shanghe","sishui","sheqi","sixian","shenzhoushi","shanglinxian","shangshuixian","shuangfeng","suichuan","shangli","shachexian","suningxian","shangchengxian","sangzhi","shimen","shanshanxian","suidexian","shaxian","shenzexian","shizhu","shaowu","shouxian","santaixian","shanzhouqu","suiningxiansnx","shuangcheng","suiping","shenmu","sqs","snj","sn","sanx","ty","ts","taizhou","tz","ta","tx","taicang","tongling","tl","tr","tc","tianshui","th","tianchang","tm","tumushuke","tongliao","tengzhou","taishan","taixing","taihexian","tongliang","tongcheng","taiqian","taihe","tiantai","taigu","tengxian","tangyin","tmtyq","tancheng","tonglu","tongan","taoyuanxian","tn","tonggu","tiandongxian","taikangxian","tongxuxian","tonghaixian","tongyuxian","tanghe","tongxinxian","tachengshi","taiwan","tongjiangxian","tonghexian","tunchangxian","tlf","taidong","taoyuan","tac","tengchong","tb","taizhong","tainan","wx","wz","wf","weihai","wuhu","xj","wn","wj","wenling","wuhai","wanzhou","wuzhou","wuan","wlcb","wd","wc","wafangdian","wuwei","wy","wugangshi","wuzhong","wangkuixian","wys","wenchang","wuxue","wanning","wg","wuding","wuzhi","wusu","wuweiww","wuhuxian","weihui","wltqq","weishan","wenshang","wucheng","weichang","ws","wuyi","wuming","weining","wuyang","wuji","wanrong","wanzai","weixian","wupingxian","weishixian","wulongxian","wuchangshi","wangcangxian","wenxian","wuzhen","wds","xm","xz","xf","xiangtan","xn","xuancheng","xianyang","xc","xy","xt","xiaogan","xx","xintai","xianning","xinyu","xan","xiantao","xh","bn","xinji","xinyi","xinzheng","xinmi","xinzhou","xinyixy","xiegangzhen","xiaoxian","xlgl","xiangxi","xingyang","xixian","xingning","xinmin","xiangcheng","xiaoyi","xiangxiang","xingcheng","xp","xiangshan","xw","xiaochangxian","xunyangxian","xiangyin","xiangshui","xinhua","xianju","xiangyuan","xuanwei","xiapu","xinan","xinxiangxian","xuyi","xuwen","xiayi","xunxian","xixiang","xiping","xinle","xinchang","xuecheng","xihua","xishui","xianghe","xinfeng","xincai","xupu","xichuan","xingan","xingguoxian","xintian","xunwuxian","xiangyunxian","xiangchengxian","xinning","xianxian","xinzhouqu","xiushantujiazumi","xinye","xianyouxian","xinjinxian","xiajin","xinzhushi","xinbei","xitang","xgll","yt","yz","yinchuan","yancheng","yy","yc","yk","yichun","yj","yuncheng","yb","yl","yiyang","yiwu","yixing","yuyao","yueqing","yulin","yongzhou","yongchuan","yf","yanzhou","yingtan","yongkang","yanbian","yq","yd","yizheng","yongcheng","yuzhou","yn","yanan","yx","yichuan","yiliangxian","yanshi","yangzhong","yutianxian","yongji","yucheng","yuxian","yangshuo","yicheng","yp","yidu","yongningxian","yh","yongjiaxian","ya","yongnian","yangcheng","yunyang","yexian","yixian","yiyangyy","yanliang","yuanyang","yuchengxian","yushan","yanggu","yunchengxian","yjhlq","yangling","yishui","yinan","yudu","yifeng","yingshanxian","yongan","yanling","yongfeng","yongxin","yongxingxian","youxian","yongshunxian","yuminxian","youyangtujiazumi","yingxian","yangshanxian","yushushi","yuanlingxian","yongdengxian","yutaixian","yizhoushi","yimashi","yuanjiang","yilan","yili","ys","yich","zz","zb","zs","zhanjiang","zj","zhuzhou","zh","zaozhuang","zhangzhou","zmd","zhoushan","zjk","zq","zunyi","zjg","zhuji","zk","zhucheng","zt","zhangye","zoucheng","zjj","zhuozhou","zhangqiu","zg","zaoyang","zunhua","zy","zhuanghe","zhaoyuan","zhungeerqi","zp","zhenxiongxian","zhijiang","zhangpu","zhangshu","zhongjiangxian","zhengding","zhongmou","zw","zhaoxian","zhecheng","zx","zhouzhi","zhijiangtongzu","zhijin","zhangping","zixingshi","zhalantunshi","zhongxian","zherong","zhongningxian","zhanghua","zhouzhuang"];// Generated by CoffeeScript 2.5.0
var API, API_URL, BODY, HTTPS, Req, SEARCH, cookie_reset, cookie_rm, dump, nexted, pathname, sleep, 进度;

sleep = (s) => {
  return new Promise((resolve) => {
    return setTimeout(resolve, s * 1000);
  });
};

(() => {
  var domain, i, now, p, s, v;
  i = 0;
  domain = document.domain;
  p = domain.split('.');
  now = new Date();
  s = now.getTime();
  now.setTime(s + 999);
  v = '_' + s + '=' + s;
  while (i < p.length - 1 && document.cookie.indexOf(v) === -1) {
    domain = p.slice(-1 - ++i).join('.');
    document.cookie = v + ';expires=' + now.toUTCString() + ';domain=' + domain + ';';
  }
  document.domain = domain;
})();

cookie_rm = function(cookieName) {
  var cookPaths, domain, pathNodes;
  domain = document.domain;
  pathNodes = location.pathname.split('/').map(function(pathWord) {
    return '/' + pathWord;
  });
  cookPaths = [''].concat(pathNodes.map(function(pathNode) {
    if (this.pathStr) {
      this.pathStr += pathNode;
    } else {
      this.pathStr = '; path=';
      return this.pathStr + pathNode;
    }
    return this.pathStr;
  }));
  (cookie_rm = function(cookieName) {
    //--- For each path, attempt to delete the cookie.
    cookPaths.forEach(function(pathStr) {
      var diagStr;
      //--- To delete a cookie, set its expiration date to a past value.
      diagStr = cookieName + '=' + pathStr + '; expires=Thu, 01-Jan-1970 00:00:01 GMT;';
      document.cookie = diagStr;
      document.cookie = cookieName + '=' + pathStr + '; domain=' + domain + '; expires=Thu, 01-Jan-1970 00:00:01 GMT;';
    });
  })(cookieName);
};

cookie_reset = function() {
  var J, cookieList, cookieName;
  cookieList = document.cookie.split(/;\s*/);
  J = cookieList.length - 1;
  while (J >= 0) {
    cookieName = cookieList[J].replace(/\s*(\w+)=.+$/, '$1');
    cookie_rm(cookieName);
    --J;
  }
};

HTTPS = "https:";

$.postJSON = function(url, data, success) {
  var contentType;
  if (typeof data !== 'string') {
    data = JSON.stringify(data);
    contentType = "application/json";
  } else {
    contentType = "text/plain";
  }
  return $.ajax(url, {
    type: 'POST',
    contentType,
    data,
    processData: false,
    success
  });
};

// $.get = (url)=>
//   new Promise (resolve, reject)=>
//     GM_xmlhttpRequest({
//       url
//       method: 'GET'
//       onload: (response) =>
//         resolve(response.responseText)
//     })
({pathname} = location);

SEARCH = "?+";

BODY = $('body');

dump = () => {
  var css, i, j, k, len, len1, li, poi, r, ref, ref1;
  r = [];
  ref = $("div[data-poiid]");
  for (j = 0, len = ref.length; j < len; j++) {
    i = ref[j];
    i = $(i);
    poi = i.data('poiid') - 0;
    
    li = [poi, i.find('.link.item-title')[0].href.split("://").pop()];
    ref1 = ['item-title', 'address', 'item-eval-info span:eq(1)', 'item-eval-info .highlight', 'avg-price'];
    for (k = 0, len1 = ref1.length; k < len1; k++) {
      css = ref1[k];
      li.push(i.find("." + css).text());
    }
    li[4] = (li[4].replace('分', '') * 10) || 0;
    li[5] = li[5].replace('人评论', '') - 0 || 0;
    li[6] = li[6].replace('人均¥', '') - 0 || 0;
    r.push(li);
  }
  return r;
};

nexted = (next, id) => {
  return new Promise((resolve) => {
    var r;
    return r = setInterval(() => {
      if (id !== ($("div[data-poiid]:first").data('poiid') - 0)) {
        clearInterval(r);
        return resolve();
      } else {
        return next.click();
      }
    }, 1000);
  });
};

Req = class Req {
  constructor(base) {
    this.base = base;
  }

  get(url) {
    return $.get(this.base + url);
  }

  postJSON(url, data) {
    arguments[0] = this.base + arguments[0];
    return $.postJSON.apply(this, arguments);
  }

};

API_URL = "//tma.xvc.com/meituan/";

API = new Req(API_URL);

进度 = (city) => {
  return (1 + CITY_EN.indexOf(city)) / CITY_EN.length;
};

(() => {
  var _keyword, begin, city, keyword, next_city, runed, title;
  begin = new Date() / 1000;
  if (location.pathname === "/error/403") {
    cookie_reset();
    if (history.length > 1) {
      history.back();
    }
    return;
  }
  if (pathname.startsWith("/s/")) {
    _keyword = pathname.split("/")[2];
    keyword = decodeURIComponent(_keyword);
    city = location.hostname.split(".")[0];
    next_city = async() => {
      var pos;
      if (city) {
        pos = CITY_EN.indexOf(city) + 1;
      } else {
        pos = 0;
      }
      if (pos >= CITY_EN.length) {
        await API.postJSON(`end/${_keyword}`);
        return location.href = API_URL + _keyword + ".csv";
      } else {
        return location.href = `//${CITY_EN[pos]}.meituan.com/s/${_keyword}` + SEARCH;
      }
    };
    if (location.search === SEARCH) {
      BODY.addClass("disable");
      runed = 进度(city);
      title = Math.round(10000 * runed) / 100 + "% · " + document.title;
      $(async() => {
        var li, next;
        while (1) {
          document.title = title;
          li = dump();
          if (li.length) {
            await API.postJSON("city", [city, keyword].concat(li));
          }
          next = $(".mt-pagination .next-btn.active");
          if (next[0]) {
            await sleep(6);
            next.click();
            if (li[0]) {
              await nexted(next, li[0][0]);
            } else {
              break;
            }
          } else {
            break;
          }
        }
        await API.postJSON(`city/${city}/${_keyword}`);
        return next_city();
      });
    } else {
      $(() => {
        var aCsv;
        aCsv = $("<a class=sA>导出</a>");
        $(".header-search-block").append(aCsv);
        return aCsv.click(async function() {
          aCsv.hide();
          city = (await API.get("q/" + keyword));
          return next_city();
        });
      });
    }
  }
  return BODY.show();
})();

//   TestObject = AV.Object.extend('TestObject')

//   number = 2018
//   string = number + ' 流行音乐榜单'
//   date   = new Date()
//   array  = [string, number]
//   object = {
//     number: number,
//     string: string
//   }

//   pointer = AV.Object.createWithoutData('Todo', '582570f38ac247004f39c24b')

//   testObject = new TestObject()
//   testObject.set('testNumber',  number)
//   testObject.set('testString',  string)
//   testObject.set('testDate',    date)
//   testObject.set('testArray',   array)
//   testObject.set('testObject',  object)
//   testObject.set('testNull',    null)
//   testObject.set('testPointer', pointer)
//   testObject.save()
